package com.fjwt.gz.service.activity.game.acte008;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityAwardBO;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.ActivitySettingEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.AwardScoreVO;
import com.fjwt.gz.db.vo.ExportAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.activity.game.DrawUtilService;
import com.fjwt.gz.service.impl.ActivityAwardService;
import com.fjwt.gz.service.impl.ActivitySettingService;
import com.fjwt.gz.service.impl.AwardSettingService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.SendAwardService;
import com.fjwt.gz.service.mapper.ScoreRecordTotalMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 转盘活动---消费者版
 *
 * @Author Will
 * @date 2023-12-19
 */
@Slf4j
@Service
public class ACTE008Service extends BaseActivityService<Object> {


    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private ScoreRecordTotalMapper recordTotalMapper;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private DrawUtilService drawUtilService;

    /**
     * 参与活动
     *
     * @return 数据异常：null; 空奖：{}；中奖：ActivityAwardVO
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("用户参加模版编号为：ACTE008 的活动");
        super.takePartIn(fansActivityDTO);
        Long fansId = fansActivityDTO.getFansId();
        Long activityId = fansActivityDTO.getActivityId();

        ActivityAwardVO activityAwardVO;
        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);
        ActivitySettingEntity activitySetting = activitySettingService.getActivitySettingEntity(activityId, redisOutTime);
        // 进行抽奖
        List<ActivityAwardAndSettingBo> awardAndSettingBos = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        Map<String, List<ActivityAwardAndSettingBo>> awardAndSettingBoMap = awardAndSettingBos.stream().collect(Collectors.groupingBy(item -> item.getAwardType() + "_" + item.getAwardId()));
        ActivityAwardBO activityAwardBO = drawUtilService.draw(activitySetting.getAwardType(), awardAndSettingBos);
        log.info("活动奖品派发数量，判断周期性次数activitySettingEntity:{}", JSONUtil.toJsonStr(activitySetting));
        if (activityAwardBO != null) {
            log.info(String.format("用户fansId:%s在本次活动activityId:%s中抽的奖品为%s", fansId, activityId, activityAwardBO.getAwardName()));
            // 积分奖品特殊处理
            if (activityAwardBO.getAwardType() == Constants.AWARD.SCORE) {
                sendAwardService.sendScore(fansId, fansActivityDTO.getAppId(), awardAndSettingBoMap.get(activityAwardBO.getAwardType() + "_" + activityAwardBO.getAwardId()).get(0), fansActivityDTO.getActivityChannelId(), false, activityEntity.getAgentNo(), activityId, Constants.SCORE.ACTIVITY);
            } else {
                // 增加获奖记录
                Long fansAwardId = sendAwardService.sendCouponOrGoods(fansId, fansActivityDTO.getAppId(), awardAndSettingBoMap.get(activityAwardBO.getAwardType() + "_" + activityAwardBO.getAwardId()).get(0), activityEntity.getPayAuthId(), fansActivityDTO.getActivityChannelId(), false, fansActivityDTO.getExtJson());
                activityAwardBO.setFansAwardId(fansAwardId);
            }
            activityAwardVO = activityAwardService.toUserData(activityAwardBO);
        } else {
            log.info(String.format("用户fansId:%s在本次活动activityId:%s中没有中奖", fansId, activityId));
            activityAwardVO = new ActivityAwardVO();
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimes = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimes)) {
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimes, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }
        return activityAwardVO;
    }

    @Override
    public void shareRun(JSONObject jsonObject) {
//        String activityId = jsonObject.getString("activityId");
//        String shareUserId = jsonObject.getString("shareUserId");
//        // 增加分享人的参与次数
//        String currentTimesKey = String.format("%s%s:%s%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.USER_FILENAME, shareUserId);//用户参会活动次数redis缓存key
//        log.info("分享人的总次数redisKey:{}", currentTimesKey);
//        ActivityUserTimesBO activityUserTimesBO = RedisUtil.getObject(currentTimesKey, ActivityUserTimesBO.class);//用户参会活动次数redis缓存
//        log.info("分享人的总次数redisValue:{}", JSONUtil.toJsonStr(activityUserTimesBO));
//
//        if (activityUserTimesBO != null) {
//            int shareAddTimes = activityUserTimesBO.getShareAddTimes();
//            activityUserTimesBO.setShareAddTimes(shareAddTimes + 1);
//        } else {
//            activityUserTimesBO = new ActivityUserTimesBO();
//            activityUserTimesBO.setShareAddTimes(1);
//        }
//        RedisUtil.set(currentTimesKey, activityUserTimesBO, redisOutTime, TimeUnit.MILLISECONDS);
    }

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE008的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("修改ACTE008的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE008的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE008的活动详情");
        return super.detail(activityId);
    }
//
//    @Override
//    public void exportActivityAward(ActivityEntity activityEntity, HttpServletResponse response) {
//        XSSFWorkbook workbook = new XSSFWorkbook();
//        List<ActivityAwardVO> awardVOS = activityAwardService.queryList(activityEntity.getActivityId());
//        // A券奖品
//        if (!awardVOS.isEmpty()) {
//            for (ActivityAwardVO a : awardVOS) {
//                if (0 == a.getAwardType()) {
//                    List<ExportAwardVO> list = fansAwardService.exportACTE008CouponAward(a.getAwardId());
//                    ACTE008ExportExcle.createCouponSheet(a.getAwardName(), workbook, list);
//                } else if (1 == a.getAwardType()) {
//                    List<ExportAwardVO> list = fansAwardService.exportACTE008GoodsAward(a.getAwardId());
//                    ACTE008ExportExcle.createGoodsSheet(a.getAwardName(), workbook, list);
//                } else if (3 == a.getAwardType()) {
//                    // 福分奖品
//                    List<AwardScoreVO> list = recordTotalMapper.exportACTE008ScoreAward(activityEntity.getActivityId());
//                    // B2奖品信息
//                    ACTE008ExportExcle.createScoreSheet(workbook, list);
//                }
//            }
//        } else {
//            throw new BizException("该活动未配置奖品！");
//        }
//        String fileName = DateUtil.current() + ".xlsx";
//        try {
//            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
//            OutputStream stream = response.getOutputStream();
//            if (null != workbook && null != stream) {
//                workbook.write(stream);
//                workbook.close();
//                stream.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
}
